package lew.bing.exp.thi;

import java.util.Scanner;
import java.util.TreeSet;
import java.util.concurrent.*;

/**
 * Created by 刘国兵 on 2018/7/22.
 */
public class TestThread {

    static class Run implements Runnable {


        @Override
        public void run() {
            synchronized (TestThread.class) {
                System.out.println(Thread.currentThread().getName() + ":运行中...");
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
//        testArrayBlock();
//        testLinkedBlock();
//        testSyn();
//        testPriority();
//        TreeSet
        new Runnable() {
            @Override
            public void run() {

            }
        } ;
    }

    public static void testPriority() {
        baseTestBlockQueue(new PriorityBlockingQueue<>(3));// 线程池如法适用优先级队列
    }

    public static void testSyn() {
        baseTestBlockQueue(new SynchronousQueue<>()); // 存在公平与不公平
    }

    public static void testLinkedBlock() {
        baseTestBlockQueue(new LinkedBlockingQueue<>(3));
    }

    public static void testArrayBlock(){
       baseTestBlockQueue(new ArrayBlockingQueue<>(3));
    }

    public static void baseTestBlockQueue(BlockingQueue<Runnable> queue) {
        /**
         * 线程池的构造方法有4,5,6，个参数
         */
        int coreSize = 2;
        int maxSize = 7;
        long times = 10;
        TimeUnit unit = TimeUnit.MILLISECONDS;
        // 这是队列有三类, ArrayBlockingQueue、LinkedBlockQueue以及SynchronousQueue
        // 存放排队的任务
        
        ThreadPoolExecutor pools = new ThreadPoolExecutor(coreSize,Integer.MAX_VALUE,times,unit,queue);
        for (int i = 0;i < 11;i++) {
//            Thread.sleep(100L); // 添加任务前先sleep，保证先来后到
            final int j = i + 1;
            try {
                pools.submit(new Run());
                System.out.println(":阻塞队列大小是" + queue.isEmpty());
                System.out.println(":线程池大小是" +pools.getPoolSize());
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("添加第"+j+"个线程失败");
            }

        }

        System.out.println("按任意键退出测试");
        Scanner scanner = new Scanner(System.in);
        scanner.nextLine();
        System.out.println("正在退出");
        pools.shutdownNow();
    }

}
